package com.tcxhb.job.agent.processor.impl;

import com.tcxhb.job.agent.constants.AgentErrorCode;
import com.tcxhb.job.agent.processor.JobProcessor;
import com.tcxhb.job.common.model.MiscResult;
import com.tcxhb.job.common.model.job.JobContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/5
 */
@Slf4j
@Component
public class ShellProcessor implements JobProcessor {
    @Override
    public MiscResult process(JobContext context) {
        List<String> commands = new ArrayList<>();
        if (SystemUtils.IS_OS_WINDOWS) {
            // Windows
            commands.add("cmd");
            commands.add("/c");
        } else {
            // Unix/Linux/MacOS
            commands.add("/bin/sh");
            commands.add("-c");
        }
        commands.add(context.getParams());
        return process(context, commands);
    }

    /**
     * 执行shell脚本
     *
     * @param commands
     * @return
     */
    public MiscResult<Boolean> process(JobContext context, List<String> commands) {
        try {
            Charset charset = System.getProperty("os.name").toLowerCase().contains("win") ? Charset.forName("GBK") : Charset.defaultCharset();
            ProcessBuilder processBuilder = new ProcessBuilder(commands);
            Process process = processBuilder.start();
            // 等待进程结束
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                return MiscResult.suc(true);
            }
            readStream(process.getErrorStream(), charset);
            return MiscResult.err(AgentErrorCode.AGENT_SHELL_EXE_ERROR);
        } catch (Exception e) {
            log.error("agent-shell-exp:" + context.getTraceId(), e);
            return MiscResult.err(AgentErrorCode.AGENT_SHELL_EXE_ERROR);
        }
    }

    protected void readStream(InputStream inputStream, Charset charset) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("shell-log:" + line);
            }
        } catch (Exception e) {
            log.error("readStream", e);
        }
    }

}
